/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.zx.mockexam.special.multiple.web;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.collect.ListUtils;
import com.jeesite.common.collect.MapUtils;
import com.jeesite.common.lang.DateUtils;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.mybatis.mapper.query.QueryType;
import com.jeesite.common.utils.excel.ExcelExport;
import com.jeesite.common.utils.excel.annotation.ExcelField.Type;
import com.jeesite.common.idgen.IdGen;
import com.jeesite.modules.sys.entity.Post;
import com.jeesite.modules.sys.service.PostService;
import com.jeesite.modules.sys.utils.DictUtils;
import com.jeesite.modules.sys.utils.UserUtils;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.zx.mockexam.special.multiple.entity.TMockeSpecialMultiple;
import com.jeesite.modules.zx.mockexam.special.multiple.service.TMockeSpecialMultipleService;
import com.jeesite.modules.zx.mockexam.special.single.entity.TmockexamSpecialSingle;
import com.jeesite.modules.zx.question.bank.entity.TquestionBank;
import com.jeesite.modules.zx.question.bank.service.TquestionBankService;

/**
 * 模拟-专项考试-多选表Controller
 * @author zpp
 * @version 2020-02-08
 */
@Controller
@RequestMapping(value = "${adminPath}/zx/mockexam/special/multiple/tMockeSpecialMultiple")
public class TMockeSpecialMultipleController extends BaseController {

	@Autowired
	private TMockeSpecialMultipleService tMockeSpecialMultipleService;
	@Autowired
	private PostService postService;
	@Autowired
	private TquestionBankService tquestionBankService;
	/**
	 * 获取数据
	 */
	@ModelAttribute
	public TMockeSpecialMultiple get(String id, boolean isNewRecord) {
		return tMockeSpecialMultipleService.get(id, isNewRecord);
	}
	
	/**
	 * 查询列表
	 */
	@RequiresPermissions("zx:mockexam:special:multiple:view")
	@RequestMapping(value = {"list", ""})
	public String list(TMockeSpecialMultiple tMockeSpecialMultiple, Model model) {
		model.addAttribute("tMockeSpecialMultiple", tMockeSpecialMultiple);
		return "modules/zx/mockexam/special/multiple/tMockeSpecialMultipleList";
	}
	
	/**
	 * 查询列表数据
	 */
	@RequiresPermissions("zx:mockexam:special:multiple:view")
	@RequestMapping(value = "listData")
	@ResponseBody
	public List<TMockeSpecialMultiple> listData(TMockeSpecialMultiple tMockeSpecialMultiple) {
		if (StringUtils.isBlank(tMockeSpecialMultiple.getParentCode())) {
			tMockeSpecialMultiple.setParentCode(TMockeSpecialMultiple.ROOT_CODE);
		}
		if (StringUtils.isNotBlank(tMockeSpecialMultiple.getObjName())){
			tMockeSpecialMultiple.setParentCode(null);
		}
		if (tMockeSpecialMultiple.getObjType() != null){
			tMockeSpecialMultiple.setParentCode(null);
		}
		if (StringUtils.isNotBlank(tMockeSpecialMultiple.getRemarks())){
			tMockeSpecialMultiple.setParentCode(null);
		}
		if (tMockeSpecialMultiple.getObjExplain() != null){
			tMockeSpecialMultiple.setParentCode(null);
		}
		if (StringUtils.isNotBlank(tMockeSpecialMultiple.getObjAnswer())){
			tMockeSpecialMultiple.setParentCode(null);
		}
		List<TMockeSpecialMultiple> list = tMockeSpecialMultipleService.findList(tMockeSpecialMultiple);
		return list;
	}

	/**
	 * 查看编辑表单
	 */
	@RequiresPermissions("zx:mockexam:special:multiple:view")
	@RequestMapping(value = "form")
	public String form(TMockeSpecialMultiple tMockeSpecialMultiple, Model model,HttpServletRequest request,HttpServletResponse response) {
		// 创建并初始化下一个节点信息
		tMockeSpecialMultiple = createNextNode(tMockeSpecialMultiple);
		Post post = new Post();
		model.addAttribute("postList", postService.findList(post));
		model.addAttribute("tMockeSpecialMultiple", tMockeSpecialMultiple);
		String objExplain=request.getParameter("objExplain");
		if(StringUtils.isNotBlank(objExplain)&&objExplain.equals("2")){
			TquestionBank quetionBank=new TquestionBank();
			quetionBank.setObjType(1);
			//查询单选
			List<TquestionBank> findList = tquestionBankService.findList(quetionBank);
			model.addAttribute("questionList",findList);
		}
		if(StringUtils.isNotBlank(objExplain)){
			return "modules/zx/mockexam/special/multiple/tMockeSpecialMultipleForm"+objExplain;
		}
		return "modules/zx/mockexam/special/multiple/tMockeSpecialMultipleForm";
	}
	@RequiresPermissions("zx:mockexam:special:multiple:view")
	@RequestMapping(value = "questionForm")
	public String questionForm(TMockeSpecialMultiple tMockeSpecialMultiple, Model model,HttpServletRequest request,HttpServletResponse response) {
		// 创建并初始化下一个节点信息
		tMockeSpecialMultiple = createNextNode(tMockeSpecialMultiple);
		String postCode=tMockeSpecialMultiple.getPost();
		TquestionBank quetionBank=new TquestionBank();
		quetionBank.setObjType(1);
		if(StringUtils.isNotBlank(postCode)){
			quetionBank.setPost(postCode);
		}else{
			quetionBank.getSqlMap().getWhere().and("post", QueryType.IS_NULL, null);
		}
		
		//查询单选
		
		List<TquestionBank> findList = tquestionBankService.findList(quetionBank);
		Post post = new Post();
		model.addAttribute("questionList",findList);
		model.addAttribute("postList", postService.findList(post));
		model.addAttribute("tMockeSpecialMultiple", tMockeSpecialMultiple);
		String objExplain=request.getParameter("objExplain");
		if(StringUtils.isNotBlank(objExplain)){
			return "modules/zx/mockexam/special/multiple/tMockeSpecialMultipleForm"+objExplain;
		}
		return "modules/zx/mockexam/special/multiple/tMockeSpecialMultipleForm";
	}
	/**
	 * 创建并初始化下一个节点信息，如：排序号、默认值
	 */
	@RequiresPermissions("zx:mockexam:special:multiple:edit")
	@RequestMapping(value = "createNextNode")
	@ResponseBody
	public TMockeSpecialMultiple createNextNode(TMockeSpecialMultiple tMockeSpecialMultiple) {
		if (StringUtils.isNotBlank(tMockeSpecialMultiple.getParentCode())){
			tMockeSpecialMultiple.setParent(tMockeSpecialMultipleService.get(tMockeSpecialMultiple.getParentCode()));
		}
		if (tMockeSpecialMultiple.getIsNewRecord()) {
			TMockeSpecialMultiple where = new TMockeSpecialMultiple();
			where.setParentCode(tMockeSpecialMultiple.getParentCode());
			TMockeSpecialMultiple last = tMockeSpecialMultipleService.getLastByParentCode(where);
			// 获取到下级最后一个节点
			if (last != null){
				tMockeSpecialMultiple.setTreeSort(last.getTreeSort() + 30);
				tMockeSpecialMultiple.setId(IdGen.nextCode(last.getId()));
			}else if (tMockeSpecialMultiple.getParent() != null){
				tMockeSpecialMultiple.setId(tMockeSpecialMultiple.getParent().getId() + "001");
			}
		}
		// 以下设置表单默认数据
		if (tMockeSpecialMultiple.getTreeSort() == null){
			tMockeSpecialMultiple.setTreeSort(TMockeSpecialMultiple.DEFAULT_TREE_SORT);
		}
		return tMockeSpecialMultiple;
	}

	/**
	 * 保存模拟-专项考试-多选表
	 */
	@RequiresPermissions("zx:mockexam:special:multiple:edit")
	@PostMapping(value = "save")
	@ResponseBody
	public String save(@Validated TMockeSpecialMultiple tMockeSpecialMultiple) {
		tMockeSpecialMultipleService.save(tMockeSpecialMultiple);
		return renderResult(Global.TRUE, text("保存模拟-专项考试-多选表成功！"));
	}

	@PostMapping(value = "saveNew")
	@ResponseBody
	public String saveNew(@Validated TMockeSpecialMultiple tMockeSpecialMultiple) {
		Integer objType = 1;
		TMockeSpecialMultiple multipletParent = tMockeSpecialMultipleService.get(tMockeSpecialMultiple.getParentCode());
		Integer category = multipletParent.getCategory();
		tMockeSpecialMultiple.setCategory(category);
		tMockeSpecialMultiple.setObjType(objType);
		tMockeSpecialMultipleService.save(tMockeSpecialMultiple);
		String id = tMockeSpecialMultiple.getId();
		String post = tMockeSpecialMultiple.getPost()==null?"":tMockeSpecialMultiple.getPost();
		Integer num = tMockeSpecialMultiple.getNumBars() == null?30:tMockeSpecialMultiple.getNumBars();

		TquestionBank quebank=new TquestionBank();
		quebank.setCategory(category);
		quebank.setObjType(objType);
		quebank.setPost(post);
		quebank.getSqlMap().getOrder().setOrderBy("RAND() LIMIT "+ num);
		List<TquestionBank> quetbankList = tquestionBankService.findList(quebank);
		int numBars = 0;
		final Double[] totalScore = {new Double(0)};
		if (quetbankList!=null && quetbankList.size()>0){
			numBars = quetbankList.size();
			quetbankList.forEach(tquestionBank->{
				totalScore[0] = totalScore[0]+tquestionBank.getScore();
				TMockeSpecialMultiple multiple = new TMockeSpecialMultiple();
				multiple.setParentCode(id);
				multiple = createNextNode(multiple);
				multiple.setCategory(category);
				multiple.setObjName(tquestionBank.getId());
				multiple.setObjType(objType);
				multiple.setPost(post);
				multiple.setScore(tquestionBank.getScore());
				multiple.setObjExplain(tMockeSpecialMultiple.getObjExplain()+1);
				tMockeSpecialMultipleService.save(multiple);
			});
		}
		tMockeSpecialMultiple.setScore(totalScore[0]);
		tMockeSpecialMultiple.setNumBars(numBars);
		tMockeSpecialMultiple.setTreeLeaf(numBars==0?"1":"0");
		tMockeSpecialMultipleService.update(tMockeSpecialMultiple);
		return renderResult(Global.TRUE, text(numBars==0?"没有获取到该类型的题目请手动增加":"保存模拟-专项考试-单选表成功！"));

	}

	/**
	 * 删除模拟-专项考试-多选表
	 */
	@RequiresPermissions("zx:mockexam:special:multiple:edit")
	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(TMockeSpecialMultiple tMockeSpecialMultiple) {
		TMockeSpecialMultiple where = new TMockeSpecialMultiple();
		where.setParentCode(tMockeSpecialMultiple.getId());
		long count = tMockeSpecialMultipleService.findCount(where);
		if (count > 0) {
			return renderResult(Global.FALSE, text("该理论模拟-专项考试-多选表成包含未删除的子项！"));
		}
		tMockeSpecialMultipleService.delete(tMockeSpecialMultiple);
		return renderResult(Global.TRUE, text("删除模拟-专项考试-多选表成功！"));
	}
	
	/**
	 * 获取树结构数据
	 * @param excludeCode 排除的Code
	 * @param isShowCode 是否显示编码（true or 1：显示在左侧；2：显示在右侧；false or null：不显示）
	 * @return
	 */
	@RequiresPermissions("zx:mockexam:special:multiple:view")
	@RequestMapping(value = "treeData")
	@ResponseBody
	public List<Map<String, Object>> treeData(String excludeCode, String isShowCode) {
		List<Map<String, Object>> mapList = ListUtils.newArrayList();
		List<TMockeSpecialMultiple> list = tMockeSpecialMultipleService.findList(new TMockeSpecialMultiple());
		for (int i=0; i<list.size(); i++){
			TMockeSpecialMultiple e = list.get(i);
			// 过滤非正常的数据
			if (!TMockeSpecialMultiple.STATUS_NORMAL.equals(e.getStatus())){
				continue;
			}
			// 过滤被排除的编码（包括所有子级）
			if (StringUtils.isNotBlank(excludeCode)){
				if (e.getId().equals(excludeCode)){
					continue;
				}
				if (e.getParentCodes().contains("," + excludeCode + ",")){
					continue;
				}
			}
			Map<String, Object> map = MapUtils.newHashMap();
			map.put("id", e.getId());
			map.put("pId", e.getParentCode());
			map.put("name", StringUtils.getTreeNodeName(isShowCode, e.getId(), e.getObjName()));
			mapList.add(map);
		}
		return mapList;
	}

	/**
	 * 修复表结构相关数据
	 */
	@RequiresPermissions("zx:mockexam:special:multiple:edit")
	@RequestMapping(value = "fixTreeData")
	@ResponseBody
	public String fixTreeData(TMockeSpecialMultiple tMockeSpecialMultiple){
		if (!UserUtils.getUser().isAdmin()){
			return renderResult(Global.FALSE, "操作失败，只有管理员才能进行修复！");
		}
		tMockeSpecialMultipleService.fixTreeData();
		return renderResult(Global.TRUE, "数据修复成功");
	}
	/**
	 * 下载导入用户数据模板
	 */
	@RequiresPermissions("zx:mockexam:special:multiple:view")
	@RequestMapping(value = "importTemplate")
	public void importTemplate(HttpServletRequest request,HttpServletResponse response) {
		TMockeSpecialMultiple entity=new TMockeSpecialMultiple();
		entity.setPage(new Page<>(request, response));
		Page<TMockeSpecialMultiple> findPage = tMockeSpecialMultipleService.findPage(entity);        
		List<TMockeSpecialMultiple> list = findPage.getList();
		for(TMockeSpecialMultiple single:list){
			Integer objExplain = single.getObjExplain();
			String dictLabel = DictUtils.getDictLabel("t_single_explain", objExplain.toString(), "未定义");
			single.setStrExplain(dictLabel);
			String postCode = single.getPost();
			if(StringUtils.isNotBlank(postCode)){
				Post post= postService.get(postCode);
				single.setPostName(post.getPostName());
			}
			Integer category = single.getCategory();
			if(category!=null){
				String categoryName = DictUtils.getDictLabel("t_examination_category", category.toString(), "未定义");
				single.setCategoryName(categoryName);
			}
			Integer difficulty = single.getDifficulty();
			if(difficulty!=null){
				String difficultyName = DictUtils.getDictLabel("t_degree_difficulty", difficulty.toString(), "未定义");
				single.setDifficultyName(difficultyName);
			}
			Integer knowledgePointType = single.getKnowledgePointType();
			if(knowledgePointType!=null){
				String knowledgePointName = DictUtils.getDictLabel("t_knowledge_point_type", knowledgePointType.toString(), "未定义");
				single.setDifficultyName(knowledgePointName);
			}
		}
		String fileName = "多选题数据模板.xlsx";
		try(ExcelExport ee = new ExcelExport("多选题数据", TMockeSpecialMultiple.class, Type.IMPORT)){
			ee.setDataList(list).write(response, fileName);
		}
	}
	/**
	 * 导入用户数据
	 */
	@ResponseBody
	@RequiresPermissions("zx:mockexam:special:multiple:edit")
	@PostMapping(value = "importData")
	public String importData(MultipartFile file, String updateSupport) {
		try {
			boolean isUpdateSupport = Global.YES.equals(updateSupport);
			String message = tMockeSpecialMultipleService.importData(file, isUpdateSupport);
			return renderResult(Global.TRUE, "posfull:"+message);
		} catch (Exception ex) {
			return renderResult(Global.FALSE, "posfull:"+ex.getMessage());
		}
	}
	/**
	 * 导出用户数据
	 */
	@RequiresPermissions("zx:mockexam:special:multiple:view")
	@RequestMapping(value = "exportData")
	public void exportData(TMockeSpecialMultiple entity, Boolean isAll, String ctrlPermi, HttpServletResponse response) {
		
		List<TMockeSpecialMultiple> list = tMockeSpecialMultipleService.findList(entity);
		for(TMockeSpecialMultiple single:list){
			Integer objExplain = single.getObjExplain();
			String dictLabel = DictUtils.getDictLabel("t_single_explain", objExplain.toString(), "未定义");
			single.setStrExplain(dictLabel);
			String postCode = single.getPost();
			if(StringUtils.isNotBlank(postCode)){
				Post post= postService.get(postCode);
				single.setPostName(post.getPostName());
			}
			Integer category = single.getCategory();
			if(category!=null){
				String categoryName = DictUtils.getDictLabel("t_examination_category", category.toString(), "未定义");
				single.setCategoryName(categoryName);
			}
			Integer difficulty = single.getDifficulty();
			if(difficulty!=null){
				String difficultyName = DictUtils.getDictLabel("t_degree_difficulty", difficulty.toString(), "未定义");
				single.setDifficultyName(difficultyName);
			}
			Integer knowledgePointType = single.getKnowledgePointType();
			if(knowledgePointType!=null){
				String knowledgePointName = DictUtils.getDictLabel("t_knowledge_point_type", knowledgePointType.toString(), "未定义");
				single.setDifficultyName(knowledgePointName);
			}
		}
		String fileName = "单选题数据" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
		try(ExcelExport ee = new ExcelExport("单选题数据", TMockeSpecialMultiple.class)){
			ee.setDataList(list).write(response, fileName);
		}
	}
}